import { find, forIn, isEmpty, pick } from 'lodash-es';


export const appConfig = {

  // 用户
  USER: {
    cn: '用户',
    modelName: 'admin',
    appCode: 'USER',
    finderCode: 'FINDER_USER',
    authConfig: {
      moduleCode: 'api_base',
      functionCode: 'user',
      actionTypes: {
        toggleState: 'toggleState',
        resetPassword:'resetPassword'
      },
    },
    api: {
      listApi: '/api/base/user/pub/query',
      detailApi: '/api/base/user/find',
      saveApi: '/api/base/user/save',
      delApi: '/api/base/user/delete',
    },
  },
  HIGHER_COMPONENT: {
    cn:'高阶组件',
    modelName:'higherComponent',
    api: {
      listApi: "xxx"
    }
  }
};

const appCodeObj = {};
forIn(appConfig, (v, k) => {
  appCodeObj[k] = v.appCode;
});

export const appCodes = appCodeObj;

/**
 * 根据 key : value ，查找对应的配置；
 * 例如：key='modelName',value='role'，即根据 modelName: 'role' 获取配置
 * @param key
 * @param value
 */
export const getConfigByKeyValue = (key, value) => {
  let configObj = null;
  if (!isEmpty(key) && !isEmpty(value)) {
    for (let k in appConfig) {
      if (appConfig.hasOwnProperty(k)) {
        let tmpO = appConfig[k];
        if (tmpO[key] === value) {
          configObj = tmpO;
          break;
        }
      }
    }
  }
  return configObj;
};

/**
 * 判断当前用户是否有权限
 * @param authConfig Object 权限配置
 * @param userAuthResObj Object 用户的权限配置
 * @returns {boolean}
 */
export function isAuthByConfig(authConfig, userAuthResObj) {
  let isAuth = false;
  if (!isEmpty(authConfig.actionTypes)) {

    for (let actionKey in authConfig.actionTypes) {
      if (authConfig.actionTypes.hasOwnProperty(actionKey)) {
        let actionVal = authConfig.actionTypes[actionKey];

        let resArr = find(userAuthResObj, (resArr) => (
          !isEmpty(resArr) && !isEmpty(find(resArr, res => (
            `${res.moduleCode}${res.functionCode}${res.actionCode}` ===
            `${authConfig.moduleCode}${authConfig.functionCode}${actionVal}`
          )))
        ));
        // 有菜单权限
        if (!isEmpty(resArr)) {
          isAuth = true;
          // console.log('resArr', resArr);
          break;
        }
      }
    }
  } else {
    isAuth = true; // 如果该菜单没有配置任何动作权限，则表示菜单是公开的
  }
  return isAuth;
}

export const isAuthByActionType = (actionType, appConfigObj, userAuthResObj) => {
  let hadAuth = true;
  if (actionType && userAuthResObj && appConfigObj) {
    const appAuthConfig = appConfigObj.authConfig || {};
    const actionTypeVal = appAuthConfig.actionTypes ? appAuthConfig.actionTypes[actionType] : '';
    const authConfig = { ...appAuthConfig, actionTypes: {} };
    authConfig.actionTypes[actionType] = actionTypeVal;
    hadAuth = isAuthByConfig(authConfig, userAuthResObj);
  }
  return hadAuth;
};
